<?php
namespace app\serverfile\logic;

use think\Db;
use \app\manage\logic\BaseLogic;
use think\Loader;
/**
 * Created by PhpStorm.
 * User: 97606
 * Date: 2017/6/23
 * Time: 10:30
 */
class File extends BaseLogic
{
    protected $name = 'file';
    protected $config = 'db_config_file';
    protected $fileModel = 'app\serverfile\model\File';
    //上传文件前 检测是否存在
    public function checkFile($type)
    {
        $md5_file = md5_file($_FILES['files']['tmp_name']);
        $res = $this->queryMd5($md5_file);
        if ($res == false) {
            return $this->upload($md5_file,$type);
        }
        $rst = $this->updateNum($md5_file,$res);
        $rst['url'] = 'http://'.$rst['save_path'].'/'.$rst['filename'];
        return vue_return($rst);
    }

    //上传文件，并将信息存入数据库
    private function upload($md5_file,$type)
    {
        $_FILES['files']['name'] = strtolower($_FILES['files']['name']);
        $_FILES['files']['type'] = strtolower($_FILES['files']['type']);
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('files');
        // 设置上传文件保存路径
        if ($type['type'] == 1) {
            $path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'private';
            $absolute_path = $_SERVER['HTTP_HOST'] . DS . 'uploads' . DS . 'private';
            $relative_path = DS . 'uploads' . DS . 'private';
            $data['type'] = 1;
        } else {
            $path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'public';
            $absolute_path = $_SERVER['HTTP_HOST'] . DS . 'uploads' . DS . 'public';
            $relative_path = DS . 'uploads' . DS . 'public';
        }
        // 设置当前日期为文件保存文件夹
        $save_name = date('Ymd',time());
        // 设置当前微秒数为文章名称 md5加密
        $filename = md5(microtime(true));
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['size'=>5242880,'ext'=>'jpg,jpeg,png,gif,pdf,txt,doc,ppt,xls'])
            ->move($path,$save_name . DS . $filename);
        if($info){
            $imageType = ['jpg','jpeg','png','gif'];
            $data['save_path']     = $absolute_path . DS . $save_name;
            $data['relative_path'] = $relative_path . DS . $save_name;
            $data['file_type']     = $info->getExtension();
            $data['save_name']     = $save_name;
            $data['filename']      = $info->getFilename();
            $data['md5_file']      = $md5_file;
            if (in_array($data['file_type'],$imageType)) {
                $src = $path . DS . $data['save_name'] . DS . $data['filename'];
                Loader::import('phpimagecompression.compression');
                $this->smallImage($src,$data,$path);
                $this->middleImage($src,$data,$path);
                $this->bigImage($src,$data,$path);
                $data['small_image'] = 'small_' . $data['filename'];
                $data['middle_image'] = 'middle_' . $data['filename'];
                $data['big_image'] = 'big_' . $data['filename'];
            }
            $createRes = $this->createInfo($data);
            if (!$createRes) {
                return auto_failure(['res' => false],'数据库信息插入失败');
            }
            $result = $this->fileGain($data); //查询后输出文件信息
            $result['url'] = 'http://'.$result['save_path'].'/'.$result['filename'];
            return vue_return($result);
        }else{
            // 上传失败获取错误信息
            $data['error'] =  $file->getError();

            return auto_failure($data);
        }
    }

    //根据文件md5值 ，检测数据库是否存在
    private function queryMd5($md5_file)
    {
        $res = $this->db()->where('md5_file',$md5_file)->find();
        if ($res == null) {
            return false;
        }
        return $res;
    }

    //文件信息保存数据库
    private function createInfo($saveData)
    {
        $saveData['upload_num'] = 1;
        $saveData['create_time'] = time();
        $saveData['update_time'] = time();
        $res = $this->db()->insert($saveData);

        if ($res == 1) {
            return true;
        }

        return false;
    }

    //压缩图片 small
    private function smallImage($src,$data,$path)
    {
        $image = new \Image($src);
        $image->percent = 0.5;
        $image->openImage();
        $image->thumpImage();
        $image->saveImage($path . DS . $data['save_name'] . DS . 'small_' . $data['filename']);
    }

    //压缩图片 middle
    private function middleImage($src,$data,$path)
    {
        $image = new \Image($src);
        $image->percent = 1.2;
        $image->openImage();
        $image->thumpImage();
        $image->saveImage($path . DS . $data['save_name'] . DS . 'middle_' . $data['filename']);
    }

    //压缩图片 big
    private function bigImage($src,$data,$path)
    {
        $image2 = new \Image($src);
        $image2->percent = 2;
        $image2->openImage();
        $image2->thumpImage();
        $image2->saveImage($path . DS . $data['save_name'] . DS . 'big_' . $data['filename']);
    }

    //更新上传次数
    private function updateNum($md5_file,$data)
    {
        $update['upload_num'] = $data['upload_num'] + 1;
        $res = $this->db()->where('md5_file',$md5_file)->update($update);

        if ($res === false) {
            return auto_failure('','数据更新异常！');
        } elseif ($res === 0) {
            return auto_failure('','没有数据发生更新！');
        }
        return $this->queryMd5($md5_file);
    }

    //删除文件 假删除
    public function fileDelete($data): array
    {
        $updateData['status'] = -1;
        $updateData['update_time'] = time();
        $rst = $this->db()
                    ->where($data)
                    ->update($updateData);
        if ($rst === false) {
            return auto_failure ($data,'文件状态更改失败！');
        } elseif ($rst === 0) {
            return auto_failure ($data,'文件状态未发生修改！');
        }
        return auto_return(['number' => $rst], '文件状态修改成功！');
    }

    //获取文件信息
    public function fileGain($data)
    {
        $res = $this->db()->where($data)->find();
        if ($res == null) {
            return auto_failure($data,"文件不存在!");
        }
        return $res;
    }

}